package com.web.netalbum.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.web.netalbum.bean.User;

public class EmailThread extends Thread {
	private User user;
	/**
	 * operator 的值为ACCOUNTACTIVED或者RESETPASSWORD
	 */
	private int operator;

	public static final int ACCOUNT_ACTIVED = 0;
	public static final int RESET_PASSWORD = 1;

	private final String account = "fangfeimonxiang@163.com";

	public EmailThread(User user, int operator) {
		this.user=user;
		this.operator = operator;
	}

	@Override
	public void run() {
		if (this.operator == ACCOUNT_ACTIVED) {
			sendAccountActivateEmail();
		} else if (this.operator == RESET_PASSWORD) {
			sendResetPasswordEmail();
		}
	}

	private Session getSession() {
		Properties properties = new Properties();
		properties.put("mail.smtp.host", "smtp.163.com");
		properties.put("mail.transport.protocol", "smtp");
		properties.put("mail.smtp.auth", "true");
		return Session.getInstance(properties);

	}

	private void sendResetPasswordEmail() {
		Session session=getSession();
		//得到transport对象
		try {
			Transport transport = session.getTransport();
			transport.connect(account,"www.fei.com");
			//得到邮件对象
			Message mess=new MimeMessage(session);
			mess.setSubject("NetAlbum重置密码邮件");
			mess.setSentDate(new Date());
			mess.setFrom(new InternetAddress(account));
			mess.setRecipient(RecipientType.TO,new InternetAddress(user.getEmail()));
			mess.setContent(" 点击链接<a href='" + GenerateLinkUtils.generateResetPwdLink(user)+"'>"+GenerateLinkUtils.generateResetPwdLink(user)+"</a>或者将链接赋值到地址栏中访问重置密码","text/html;charset=utf-8");  
			transport.sendMessage(mess, mess.getAllRecipients());
			transport.close();
		} catch (Exception e) {
		// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	private void sendAccountActivateEmail() {
		Session session=getSession();
		//得到transport对象
		try {
			Transport transport = session.getTransport();
			transport.connect(account,"www.fei.com");
			//得到邮件对象
			Message mess=new MimeMessage(session);
			mess.setSubject("NetAlbum账户激活邮件");
			mess.setSentDate(new Date());
			mess.setFrom(new InternetAddress(account));
			System.out.println(user.getEmail());
			mess.setRecipient(RecipientType.TO,new InternetAddress(user.getEmail()));
			mess.setContent("欢迎您注册NetAlbum 点击链接<a href='" + GenerateLinkUtils.generateActivateLink(user)+"'>"+GenerateLinkUtils.generateActivateLink(user)+"</a>或者将链接赋值到地址栏中访问来激活账户","text/html;charset=utf-8");  
			transport.sendMessage(mess, mess.getAllRecipients());
			transport.close();
		} catch (Exception e) {
		// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
